/*java jdk 1.7+
# -*- coding: utf-8 -
'''
Created on 2020年05月10日
@author: zxyong 13738196011
'''*/

package com.zxy.tcp;

import java.io.IOException;

import org.eclipse.paho.client.mqttv3.MqttClient;
import org.eclipse.paho.client.mqttv3.MqttConnectOptions;
import org.eclipse.paho.client.mqttv3.MqttException;
import org.eclipse.paho.client.mqttv3.MqttTopic;
import org.eclipse.paho.client.mqttv3.persist.MemoryPersistence;

import com.zxy.adminlog.UsAdmin_Log;
import com.zxy.common.Com_Fun;
import com.zxy.common.Com_Para;

public class MqttHandler extends Thread
{
	public void run()
	{
		try
		{
			this.setName("MqttHandler_zxyong");
			if(java.util.Objects.equals(Com_Para.mqclient,null))
			{
				Com_Para.mqclient = new MqttClient(Com_Para.MQTT_host,"zxy_mq_server",new MemoryPersistence());
				MQTTconnect();
			}
		}
		catch(Exception e)
		{
			Com_Fun.debug_in(e,this.toString());
		}
	}

	private void InitTopic() throws MqttException
	{
		if(Com_Para.htMqttTopicPull.size() == 0
				&& !Com_Para.MQTT_topic_pull.equals(""))
		{
			Com_Para.htMqttTopicPull.clear();
			for(String strtopic: Com_Para.MQTT_topic_pull.split(","))
			{
				MqttTopic topic = Com_Para.mqclient.getTopic(strtopic);
				Com_Para.htMqttTopicPull.put(strtopic,topic);
			}
		}

		if(Com_Para.htMqttTopicGet.size() == 0
				&& !Com_Para.MQTT_topic_get.equals(""))
		{
			Com_Para.htMqttTopicGet.clear();
			for(String strtopic: Com_Para.MQTT_topic_get.split(","))
			{
				MqttTopic topic = Com_Para.mqclient.getTopic(strtopic);
				Com_Para.htMqttTopicGet.put(strtopic,topic);
			}

			int[] Qos = new int[Com_Para.MQTT_topic_get.split(",").length];
			for(int i = 0;i < Qos.length;i++)
			{
				Qos[i] = 2;
			}
			Com_Para.mqclient.subscribe(Com_Para.MQTT_topic_get.split(","),Qos);
		}
	}

	public void MQTTconnect()
	{
		MqttConnectOptions options = new MqttConnectOptions();
		options.setCleanSession(true);
		options.setUserName(Com_Para.MQTT_username);
		options.setPassword(Com_Para.MQTT_pwd.toCharArray());
		// 设置超时时间
		options.setConnectionTimeout(10);
		// 设置会话心跳时间
		options.setKeepAliveInterval(20);
		try
		{
			Com_Para.mqclient.setCallback(new PushCallback());
			Com_Para.mqclient.connect(options);
			InitTopic();
		}
		catch(Exception e)
		{
			Com_Fun.debug_in(e,this.toString());
		}
	}
}